package at.fhj.itm10.ticketmaster.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import at.fhj.itm10.ticketmaster.entities.Customer;
import at.fhj.itm10.ticketmaster.services.ServiceFactory;

/**
 * checks if entered username is unique
 * 
 * @author Sabrina Gruber
 */
@FacesValidator(value="UniqueUsernameValidator")
public class UniqueUsernameValidator implements Validator {
 
	public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) {
  
	    String userName = (String) object;
	    boolean alreadyExists = false;
	  
		ServiceFactory factory = new ServiceFactory();
		Customer userList = factory.getCustomerService().findByUsername(userName);
	    if (userList != null) {
	    	alreadyExists = true;
	    }
	
	    if(alreadyExists == true) {
	    	FacesMessage message = new FacesMessage();
	    	message.setDetail("Dieser Username existiert bereits. Bitte geben Sie einen anderen ein.");
	
	    	message.setSeverity(FacesMessage.SEVERITY_ERROR);
	    	throw new ValidatorException(message);
	    }
	}
}